/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */

$(function () {
    org.breezee.page = {
        init: function () {
            var loginCustomerId = $("#_loginCustomerId").val();
            var loginAccountId = $("#_loginAccountId").val();
            var loginVendorId = $("#_loginVendorId").val();
            if((loginCustomerId != null && loginCustomerId != "")
                || (loginVendorId != null && loginVendorId != "")){

                /*var optionUrl="/api/c666378c5d3b417d8e150c456a489d23@accountId="+loginAccountId;
             var ajaxType="get"
             var optionParam='{"properties":{}}'
             $("#customer_select").attr("optionUrl",optionUrl)
                 .attr("ajaxType",ajaxType)
                 .attr("optionParam", optionParam);*/

                let _this = $("#customer_select");
                Dolphin.ajax({
                    url: '/api/c666378c5d3b417d8e150c456a489d23@accountId='+loginAccountId,
                    type: Dolphin.requestMethod.GET,
                    async : false,
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
                $("#customer_select").select2();

            }else{
                /*var optionUrl="/api/742445c653654caaa4a1fa69eb651a9a"
                var ajaxType="post"
                var optionParam = '{"properties":{"category":"1"}}';
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);*/
                let _this = $("#customer_select");
                Dolphin.ajax({
                    url: '/api/742445c653654caaa4a1fa69eb651a9a',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : {"category":"1"}}),
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
                $("#customer_select").select2();
            }

            Dolphin.form.parse();
            this.initEvent();
            this._userList = this.userList('#userList');

            var loginCustomerId = org.breezee.context.userData.customerId;
            var shopCondition = {"selectCustomerId": loginCustomerId};
            if (loginCustomerId) {
                var shs = $("#shop_select");
                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async: false,
                    data: Dolphin.json2string({properties: shopCondition}),
                    onSuccess: function (reData) {
                        shs.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows, function (index, obj) {
                            shs.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
            }
            $(".js-example-basic-single").select2();

        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            let me = this;

            /**
             * 绑定回车事件，触发搜索
             */
            $(document).keypress(function(e) {
                var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
                if (eCode == 13){
                    $(".btn-query").click();
                }
            });

            $('.content-refresh').click(function () {
                me._userList.reload();
            });

            //选择客户
            $("#customer_select").change(function(){

                $("#shop_select").empty();

                var queryConditionObj = {};
                queryConditionObj.selectCustomerId = $(this).val();
                if($("#followedFlag").is(':checked')){
                    queryConditionObj.followed = 'Y';
                }
                queryConditionObj.selectShopType = $("#shopType").val();

                var _this = $("#shop_select");

                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : queryConditionObj}),
                    onSuccess: function (reData) {

                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });

            });

            //选择门店类型
            $("#shopType").change(function(){

                $("#shop_select").empty();

                var queryConditionObj = {};
                queryConditionObj.selectCustomerId = $("#customer_select").val()|| $("#_loginCustomerId").val();
                if($("#followedFlag").is(':checked')){
                    queryConditionObj.followed = 'Y';
                }
                queryConditionObj.selectShopType = $(this).val();

                var _this = $("#shop_select");

                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : queryConditionObj}),
                    onSuccess: function (reData) {

                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });

            });

            //查询
            $(".btn-query").click(function () {
                var shopIds = '';
                var shopsCondition = $(".shop_select").val();//查询条件 店铺
                var shopTypeCondition = $("#shopType").val();//查询条件 店铺类型
                var shopAreaCondition = $("#customer_select").val();//查询条件 区域
                if (shopsCondition != null && shopsCondition.length > 0) {
                    shopIds = shopsCondition;
                } else if ((shopTypeCondition != null && shopTypeCondition.length > 0)
                    || (shopAreaCondition != null && shopAreaCondition.length > 0)) {
                    Dolphin.ajax({
                        url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                        type: Dolphin.requestMethod.POST,
                        data: Dolphin.json2string({
                            properties: {
                                "selectCustomerId": shopAreaCondition,
                                "selectShopType": shopTypeCondition
                            }
                        }),
                        async: false,
                        loading: true,
                        onSuccess: function (reData) {
                            shopIds = '';
                            if (reData.rows) {
                                var shopIdArray = $.map(reData.rows, function (n) {
                                    return n.id;
                                });
                                shopIds = shopIdArray.join(',');
                            }
                        }
                    });
                }
                var queryCondition = Dolphin.form.getValue('.query-form');
                queryCondition.customer_id_obj_in_ae = shopIds;
                queryCondition.happenTime_gt = queryCondition._startDate.replace(/-/g, '') + "000000";
                queryCondition.happenTime_le = queryCondition._endDate.replace(/-/g, '') + "000000";
                console.log(queryCondition);
                if(!queryCondition._startDate || !queryCondition._endDate){
                    Dolphin.alert(Dolphin.i18n.get("equipment.rangeData"));
                    return;
                }else{
                    var startDate1 = Dolphin.string2date(queryCondition._startDate+' 00:00:00','yyyy-MM-dd hh:mm:ss');
                    var endDate1 = Dolphin.string2date(queryCondition._endDate+' 23:59:59','yyyy-MM-dd hh:mm:ss');
                    var cntDay1 = Math.ceil(Math.abs(endDate1.getTime() - startDate1.getTime()) / 1000/ 60/ 60/ 24);
                    if(cntDay1 > 7){
                        Dolphin.alert(Dolphin.i18n.get("equipment.suggested"));
                        return;
                    }
                }
                me._userList.load('/api/1d618fadeb6b4f588eebe74f965ec731', queryCondition);

                //重置进店总数，出点总数
                Dolphin.ajax({
                    url: '/api/1d618fadeb6b4f588eebe74f965ec731',
                    type: Dolphin.requestMethod.POST,
                    loading:true,
                    data: Dolphin.json2string({properties : queryCondition}),
                    onSuccess: function (reData) {
                        $("#inCnt").html(reData.extProps.inCnt);
                        $("#outCnt").html(reData.extProps.outCnt);
                    }
                });
            });
        },
        userList: function (panelId) {
            let me = this;
            $(panelId).empty();
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                queryParams: {
                    customerId: org.breezee.context.userData.customerId
                },
                columns: [{
                    code: 'sn',
                    title: Dolphin.i18n.get("framework.equipmentCode"),
                    width: '150px'
                }, {
                    code: 'position',
                    title: Dolphin.i18n.get("framework.equipmentPosition"),
                    width: '150px'
                }, {
                    code: 'shopName',
                    title: Dolphin.i18n.get("sales.storeName")
                }, {
                    code: 'dxin',
                    title: Dolphin.i18n.get("equipment.entry"),
                    width: '100px',
                    textAlign: 'right',
                }, {
                    code: 'dxout',
                    title: Dolphin.i18n.get("equipment.exit"),
                    width: '100px',
                    textAlign: 'right',
                }, {
                    code: 'happenTime',
                    title: Dolphin.i18n.get("equipment.dataTime"),
                    width: '180px',
                    formatter: function (val) {
                        val = val + "";
                        if (val.length > 10) {
                            return val.substr(0, 4) + "-" + val.substr(4, 2) + "-" + val.substr(6, 2) + " "
                                + val.substr(8, 2) + ":" + val.substr(10, 2) + ":" + val.substr(12, 2);
                        } else {
                            return "";
                        }
                    }
                }, {
                    code: 'modifiedDate',
                    title: Dolphin.i18n.get("equipment.updatingTime"),
                    width: '180px'
                }],
                pageSize: 10,
                multiple: true,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                pagination: true,
                onLoadSuccess: function () {

                }
            });
        }
    };
    org.breezee.page.init();
});